<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2023/3/13
 * Time: 11:16
 */

namespace App\Rep;


use App\Models\DispatchOrder;
use App\Models\Employee;
use App\Models\EmployeeJobType;
use App\Models\JobType;
use App\Models\ModelFields;
use App\Models\ModelNumberUser;
use App\Models\Models;
use App\Models\Order;
use App\Models\OrderChild;
use App\Models\Product;
use App\Models\ProductJobType;
use App\Models\Rbac\User;
use App\Models\Rbac\UserRole;
use Illuminate\Support\Facades\DB;


class EmployeeRep
{
    /**
     * 获取员工列表
     * @param $params
     * @return mixed
     */
    public function getEmployeeListRep($params){
        $params['roles_id'] = 16;
        //$list = User::Search($params)->with(['employee','role'])->orderBy('id','desc')->paginate($params['per_page']??10);
        $list = Employee::Search($params)
            ->with(['user'=>function($q){
                $q->with(['role']);
            },'job_type'])
            ->orderBy('id','desc')->paginate($params['per_page']??10);
        return $list;
    }

    /**
     * 添加员工
     * @param $params
     * @return Employee|array
     */
    public function createEmployeeRep($params){
        DB::beginTransaction();
        try{

            if(isset($params['id']) && !empty($params['id'])){
                //编辑
                $user = User::where('id',$params['id'])->first();
                $user->company_name = $params['employee_name']??'';
                $user->phone = $params['phones']??'';
                $user->username = $params['usernames'];
                $user->password = $params['passwords']??88888888;

            }else{
                $user = User::where('username',$params['usernames'])->first();
                if($user){
                    return ['code'=>1011,'data'=>[],'msg'=>''];
                    //$user->username = $params['usernames'];
                }else{
                    $user = new User();
                    $user->username = $params['usernames'];
                    $user->password = $params['passwords']??123456;
                    $user->phone = $params['phones']??"";
                    $user->company_name = $params['employee_name']??'';
                    $user->parent_username = $params['username'];
                }

            }
            $user->save();
            $where = ['user_id'=>$user->id];
            UserRole::updateOrCreate($where,['role_id'=>$params['roles_id']??16]);
            $employee_info = [
                "employee_name" => $params['employee_name'],
                "user_id"=>$user->id,
                "phone" => $params['phones']??"",
                "address" => $params['address']??'',
                "job_type_id" => $params['job_type_id'],
                "id_card" => $params['id_card']??'',
                "native_place" => $params['native_place']??'',
                "emergency_contact" => $params['emergency_contact']??'',
                "emergency_contact_phone" => $params['emergency_contact_phone']??'',
                "card_number" => $params['card_number']??null,
                "base_pay" => $params['base_pay']??'',
                "hiredate" => $params['hiredate']??'',
                "submit_way" => $params['submit_way'],
            ];
            Employee::updateOrCreate($where,$employee_info);
            $model = User::with(['role','employee'])->find($user->id);
            DB::commit();
            return ['code'=>0,'data'=>$model,'msg'=>''];
        }catch(\Exception $e){
            DB::rollBack();
            return ['code'=>2001,'data'=>[],'msg'=>$e->getMessage()];
        }

    }

    /**
     * 删除员工
     * @param $params
     */
    public function delEmployeeRep($params){
        $model = Employee::where('id',$params['id'])->first();
        $model->is_del = $params['is_del'];
        $model->save();
        return $model;
    }

    /**
     * 根据type_job_id获取员工列表
     * @param $params
     */
    public function getEmployeeListByJobTypeIDRep($params){
        return Employee::where('is_del',2)->where('job_type_id',$params['job_type_id'])->get();
    }

    /**
     * 查询员工可领取订单
     * 1.指派的订单
     * 2.工种未领取的订单
     * 备注：排序按派单顺序设置
     * 工种可领几条数据就显示几条数据
     */
    public function searchPensionableOrderChildRep($params){
        //p(111);
        $employee_user_id = $params['user_id'];

        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        if($employeeInfo['unclaimed_num']<=0){
            return ['code'=>1017,'data'=>[],'msg'=>'不可领取多个工单'];
        }

        $job_type_id = $this->getJobTypeIdByEmployeeUserId($employee_user_id);
        //p($job_type_id);
        $orderByArr = (new DispatchOrderRep())->getDispatchOrderSortRep();
        $list = OrderChild::where('order_child.is_del',"<>",1)->where('order.status',1)
            ->where(function($q)use($employee_user_id,$job_type_id){
                $q->orwhere(function($q)use($employee_user_id){
                    //指派
                    $q->where('order_child.status',3)
                        ->where('order_child.employee_user_id',$employee_user_id)
                        ->where('order_child.is_appoint',1);
                })->orwhere(function($q)use($job_type_id){
                    $q->where('order_child.job_type_id',$job_type_id)
                        ->where('order_child.is_epiboly',2)//是否外包
                        ->where('order_child.is_appoint',2)//是否指派
                        ->where('order_child.status',3);
                });
                //->whereNull('order_child.submit_time')
                //->whereNull('order_child.draw_time');//领取时间
            })->with(['job_type','employee','order'=>function($q){
                return $q->with(['color'=>function($q){
                    return $q->select('id','color');
                },'product'=>function($q){
                    return $q->select('id','product_name');
                },'customer'=>function($q){
                    return $q->select('id','customer_name','customer_address');
                },'modelNumber'=>function($q){
                    return $q->select('id','model_number');
                },'specification'=>function($q){
                    return $q->select('id','specification');
                },'finish_product'=>function($q){
                    return $q->select('order_id','num','warehouse_id','goods_shelf_id');
                }]);
            }]) ->join('order', 'order.id', '=', 'order_child.order_id')
            ->select(
                'order_child.*',
                'order.id as orders_id',
                'order.color_id',
                'order.customer_id',
                'order.model_number_id',
                'order.product_id',
                'order.status')
            ->orderBy($orderByArr[0]['field_name'],$orderByArr[0]['sortord'])
            ->orderBy($orderByArr[1]['field_name'],$orderByArr[1]['sortord'])
            ->orderBy($orderByArr[2]['field_name'],$orderByArr[2]['sortord'])
            ->orderBy($orderByArr[3]['field_name'],$orderByArr[3]['sortord'])
            //->skip(0)->take($employeeInfo['unclaimed_num'])
            //->offset(0)
            //->limit($employeeInfo['unclaimed_num'])
            ->get();
        //p($list->toArray());
        $count = 1;
        foreach($list as $k=>$v){
            if($count>$employeeInfo['unclaimed_num']){
                unset($list[$k]);
                continue;
            }
            $jobTypeRep = new JobTypeRep();
            $is_restrict = $jobTypeRep->judgeIsRestrict($v->job_type_id,$v->product_id);
            //p($is_restrict);
            //是否限制流程
            if($is_restrict){
                //限制流程，判断上个工序是否完成
                $res = $this->judgeLastProcess($v->order_id,$v->job_type_id,$v->product_id);
                //p($res);
                if(!$res){
                    //return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
                    unset($list[$k]);
                }
            }
            $count++;
        }

        return $list;
    }

    /**
     * 获取员工的工种id
     * @param $employee_user_id
     * @return $job_type_id
     */
    public function getJobTypeIdByEmployeeUserId($employee_user_id){
        $employee = Employee::where('user_id',$employee_user_id)->first();
        return $employee->job_type_id;
    }

    /**
     * 员工领取订单
     * @param $params
     * user_id
     * order_child_id
     */
    public function drawOrderChildRep($params){
        //p($params);
        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        if($employeeInfo['unclaimed_num']<=0){
            return ['code'=>1017,'data'=>$employeeInfo,'msg'=>'不可领取多个工单'];
        }
        if(isset($params['order_child_id']) && !empty($params['order_child_id'])){
            $order_child_id = $params['order_child_id'];
        }else{
            $order_child_id = OrderChild::where('order_id',$params['order_id'])->where('job_type_id',$employeeInfo['job_type_id'])->value('id');
        }
        //p($order_child_id);
        $order_child = OrderChild::where('id',$order_child_id)->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type'])->first();
        if(!empty($order_child['draw_time'])){
            return ['code'=>1023,'data'=>$employeeInfo,'msg'=>'该工单已领取，无需再次领取'];
        }

        //指派的员工才能领取
        if($order_child['is_appoint'] == 1){
            if($params['user_id'] != $order_child['employee_user_id']){
                return ['code'=>1025,'data'=>$employeeInfo,'msg'=>'该工单已指派，无法领取'];
            }
        }

        $order = Order::where('id',$order_child->order_id)->first();
        //订单等级等于员工等级才能领取
//        if($order->level != 0){
//            if($employeeInfo['level'] != $order->level){
//                return ['code'=>1024,'data'=>$employeeInfo,'msg'=>'该工单的订单等级与员工等级不匹配'];
//            }
//        }

        $jobTypeRep = new JobTypeRep();
        $is_restrict = $jobTypeRep->judgeIsRestrict($order_child->job_type_id,$order_child->order->product_id);
        if($is_restrict){
            //限制流程，判断上个工序是否完成
            $res = $this->judgeLastProcess($order_child->order_id,$order_child->job_type_id,$order_child->order->product_id);
            if(!$res){
                return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
            }
        }
        $order_child->employee_user_id = $params['user_id'];
        $order_child->draw_time = date("Y-m-d H:i:s",time());
        $order_child->operator_user_id = $params['user_id'];
        $order_child->status = 2;
        $order_child->save();
        $order_child = OrderChild::where('id',$order_child_id)->with(['order'=>function($q){
            return $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type'])->first();
        return ['code'=>0,'data'=>$order_child,'msg'=>'success'];
    }

    /**
     * 提交订单
     */
    public function submitOrderChildRep($params){
        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        $order_child_id = OrderChild::where('order_id',$params['order_id'])->where('job_type_id',$employeeInfo['job_type_id'])->value('id');
        $order_child = OrderChild::where('id',$order_child_id)->first();
        $order = Order::find($params['order_id']);

        if(!empty($order_child->submit_time) && $order_child->status = 1){
            return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
        }
        if($order_child['is_appoint'] == 1){
            if($params['user_id'] != $order_child->employee_user_id){
                return ['code'=>1026,'data'=>[],'msg'=>'这不是你的订单,已指派'];
            }
            if(empty($order_child->draw_time)){
                $order_child->draw_time = date("Y-m-d H:i:s",time());
                $order_child->status = 2;
                $order_child->save();
                return ['code'=>0,'data'=>[],'msg'=>'领取成功'];
            }

        }elseif ($order_child['is_appoint'] == 2){
//            $ress = ModelNumberUser::where('model_number_id',$order->model_number_id)->where('job_type_id',$employeeInfo['job_type_id'])->where('user_id',$params['user_id'])->first();
//            if(!$ress){
//                return ['code'=>1026,'data'=>[],'msg'=>'你无权领取当前订单'];
//            }
            if($order_child->employee_user_id == null){
                $order_child->employee_user_id = $params['user_id'];
                $order_child->draw_time = date("Y-m-d H:i:s",time());
                $order_child->status = 2;
                $order_child->save();
                return ['code'=>0,'data'=>[],'msg'=>'领取成功'];
            }
        }



        $res = $this->judgeLastProcess($params['order_id'],$employeeInfo['job_type_id'],$order->product_id);
        //p($res);
        if(!$res){
            return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
        }

        $order_child->submit_time = date("Y-m-d H:i:s",time());
        $order_child->status = 1;
        if(!empty($params['image1']??'')){
            $order_child->image1 = $params['image1'];
        }
        if(!empty($params['image2']??'')){
            $order_child->image2 = $params['image2'];
        }
        if(!empty($params['image3']??'')){
            $order_child->image3 = $params['image3'];
        }
        if(!empty($params['image4']??'')){
            $order_child->image4 = $params['image4'];
        }
        $order_child->save();
        $orderRep = new OrderRep();
        $orderRep->selectOrderChildStatus($order_child->order_id);
        return ['code'=>0,'data'=>$order_child,'msg'=>'提交成功'];
    }

    /**
     * 打印 提交订单
     */
    public function submitOrderChildByDayinRep($params){
        $employeeInfo = $this->setEmployeeInfo($params['user_id']);
        $order = Order::where('order_number',$params['order_number'])->first();
        $order_child_id = OrderChild::where('order_id',$order->id)->where('job_type_id',$employeeInfo['job_type_id'])->value('id');
        $order_child = OrderChild::where('id',$order_child_id)->first();
        if(!$order){
            return ['code'=>2003,'data'=>[],'msg'=>'订单号错误！'];
        }

        if(!empty($order_child->submit_time) && $order_child->status = 1){
            return ['code'=>1022,'data'=>[],'msg'=>'该工单已提交，无需再次提交'];
        }

        if($order_child->is_appoint == 1){
            if($params['user_id'] != $order_child->employee_user_id){
                return ['code'=>1026,'data'=>[],'msg'=>'这不是你的订单,已指派'];
            }
            if(empty($order_child->draw_time)){
                $order_child->draw_time = date("Y-m-d H:i:s",time());
                $order_child->status = 2;
                $order_child->save();
                return ['code'=>0,'data'=>[],'msg'=>'领取成功'];
            }

        }elseif ($order_child->is_appoint == 2){
            $ress = ModelNumberUser::where('model_number_id',$order->model_number_id)->where('job_type_id',$employeeInfo['job_type_id'])->where('user_id',$params['user_id'])->first();
            if(!$ress){
                return ['code'=>1026,'data'=>[],'msg'=>'你无权领取当前订单'];
            }
            if($order_child->employee_user_id == null){
                $order_child->employee_user_id = $params['user_id'];
                $order_child->draw_time = date("Y-m-d H:i:s",time());
                $order_child->status = 2;
                $order_child->save();
                return ['code'=>0,'data'=>[],'msg'=>'领取成功'];
            }
        }
        $res = $this->judgeLastProcess($order->id,$employeeInfo['job_type_id'],$order->product_id);
        //p($res);
        if(!$res){
            return ['code'=>1018,'data'=>[],'msg'=>'限制流程，有尚未完成的工序'];
        }

        $order_child->submit_time = date("Y-m-d H:i:s",time());
        $order_child->status = 1;
        if(!empty($params['image1']??'')){
            $order_child->image1 = $params['image1'];
        }
        if(!empty($params['image2']??'')){
            $order_child->image2 = $params['image2'];
        }
        if(!empty($params['image3']??'')){
            $order_child->image3 = $params['image3'];
        }
        if(!empty($params['image4']??'')){
            $order_child->image4 = $params['image4'];
        }
        $order_child->save();
        $orderRep = new OrderRep();
        $orderRep->selectOrderChildStatus($order_child->order_id);
        return ['code'=>0,'data'=>$order_child,'msg'=>'提交成功'];
    }





    /**
     * 查询【已完成/未完成】的订单
     * @param $params
     */
    public function searchCompletedOrUnfinishedOrderChildRep($params){
        $status = $params['status']??1;
        $model = OrderChild::where('employee_user_id',$params['user_id'])
            ->where('is_del','<>','1')
            ->with(['order'=>function($q){
             $q->with(['customer','modelNumber','color','specification']);
        },'employee','job_type']);
        if($status == 1){
            $list = $model->where('status',$status)->whereNotNull('submit_time')
                ->paginate($params['per_page']??10);
        }elseif($status == 2){
            $list = $model->where('status',$status)->whereNull('submit_time')
                ->paginate($params['per_page']??10);
        }
        $list = $list->toArray();
        $data = $list['data'];
        if($data){
            foreach($data as $k=>$v){
                $product_id = $v['order']['product_id'];
                $modelid = Product::where('id',$product_id)->value('modelid');
                $tablename = Models::where('modelid',$modelid)->value('tablename');
                $model_field = ModelFields::where('modelid',$modelid)->get();

                if($model_field){
                    foreach($model_field as $kk=>$vv){
                        if(in_array($vv->formtype,['input','textarea','inputnumber'])){
                            $data[$k]['order']['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['order']['id'])->value($vv->field);
                        }else{
                            if(!empty($vv->option_list)){
                                $option_list = explode("\n",$vv->option_list);
                                //p($option_list);
                                $option_arr = [];
                                foreach($option_list as $key=>$val){
                                    $option = explode("|",rtrim($val));
                                    //p($option);
                                    $option_arr[$option[1]] = $option[0];
                                }
                                $field_key = DB::table($tablename)->where('order_id',$v['order']['id'])->value($vv['field']);
                                $data[$k]['order']['models_field'][$vv->field] = $field_key;
                                $data[$k]['order']['models_field'][$vv->field."s"] = $option_arr[$field_key]??'';
                                //$data[$k]['models_field'][$vv->field] = ['value'=>$option_arr[$field_key]??'','key'=>$field_key];
                            }else{
                                $data[$k]['order']['models_field'][$vv->field] = DB::table($tablename)->where('order_id',$v['order']['id'])->value($vv['field']);
                            }
                        }
                    }
                }

            }
        }
        $list['data'] = $data;
        return $list;
    }

    /**
     * 判断上一个工序是否完成
     */
    public function judgeLastProcess($order_id,$job_type_id,$product_id){
        $product_job_type = ProductJobType::where('job_type_id',$job_type_id)->where('product_id',$product_id)->first();
        $sort = $product_job_type->sort;
        $pid = $product_job_type->pid;
        if($sort>1){
            $pid_arr = explode(',',$pid);
            foreach($pid_arr as $k=>$v){
                $status = OrderChild::where('order_id',$order_id)->where('job_type_id',$v)->value('status');
                if($status != 1){
                    return false;
                    break;
                }
            }
        }
        return true;
    }

    /**
     * 设置员工登录，员工基本信息
     * @param $user_id
     */
    public function setEmployeeInfo($user_id){
        $info = User::where('id',$user_id)->first();
        //p($info);
        $employee = Employee::where('user_id',$user_id)->with('job_type')->first();
        //p($employee->toArray());
        $job_type = $employee->job_type;
        //p($job_type);
        //可领单数
        $arr['multi_order_num'] = 1;
        if($job_type->is_multi == 1){
            $arr['multi_order_num'] = $job_type->multi_order_num;
        }
        //已领单数
        $arr['already_received_num'] = OrderChild::where('status',2)->where('employee_user_id',$user_id)->count();
        //未领取数
        $arr['unclaimed_num'] = $arr['multi_order_num'] - $arr['already_received_num'];
        $arr['level'] = $employee->level;
        $arr['job_type_id'] = $employee->job_type_id;
        return $arr;
    }





}
